<?php
class Admin_ArticleResource extends BaseController
{
     protected $layout = 'layouts.admin';
	 protected $validatorMessages = array(
	  'title.required'      => '请输入文章名。',
	  'class.required'      => '请选择文章分类。',
	  'keys.required'      => '请输入关键字。',
	  'info.required'      => '请选择文章简介。',
	  'content.required'      => '请选择文章内容。',
	);


	public function index()
	{
		$law_cat = Input::get('law_cat');
		$class = Input::get('class');
		$keywords = Input::get('keywords');
		$orderColumn = Input::get('sort_up', Input::get('sort_up', 'created_at'));
		$direction   = Input::get('sort_up') ? 'asc' : 'desc' ;

		$law_cat_list = Article::getArticleClassList('请选择', 'law_category');
        $type_instrument_list = Article::getArticleClassList('请选择', 'type_instrument');
		$article_class_list = Article::getArticleClassList('请选择', 'article');
		
		// 取文章数据
		$article_model = App::make('Article');
		$query = $article_model->orderBy($orderColumn, $direction);
		if($class)$query->where("class", $class);
		if($law_cat)$query->where("law_cat", $law_cat);
		if($keywords)$query->whereRaw("title LIKE '%".$keywords."%'");
		$datas = $query->paginate(Config::get('app.page_row'));
		$this->layout->content = View::make('admin.article.index')->with(compact('datas', 'law_cat_list', 'type_instrument_list', 'article_class_list', 'keywords', 'law_cat', 'class'));				
	}

	/**
	 * 列出律师创建的articles
	 */
	public function fromLawyer()
	{
		$status = Input::get('status');
		$law_cat = Input::get('law_cat');
		$class = Input::get('class');
		$keywords = Input::get('keywords');
		$orderColumn = Input::get('sort_up', Input::get('sort_up', 'created_at'));
		$direction   = Input::get('sort_up') ? 'asc' : 'desc' ;

		$law_cat_list = UtilsHelper::workScopeKeyValue();
		$article_class_list = Article::getArticleClassList('请选择', 'article');
		$status_list = ['null' => '请选择', 0 => '未审核', 1 => '已通过审核', 2 => '草稿', -1 => '审核不通过'];
		
		// 取文章数据
		$article_model = App::make('Article');
		$query = $article_model->orderBy($orderColumn, $direction);
		if($class)$query->where("class", $class);
		if($law_cat)$query->where("law_cat", $law_cat);
		if($keywords)$query->whereRaw("title LIKE '%".$keywords."%'");
		$query->where("from_admin", false);
		if (!is_null($status) && $status !== 'null') {
			$query->where("status", $status);
		}
		$datas = $query->paginate(Config::get('app.page_row'));
		$this->layout->content = View::make('admin.article.from_lawyer')->with(
			compact('datas', 'law_cat_list', 'status_list', 'article_class_list', 'keywords', 'law_cat', 'class', 'status'));				
	}

	/**
	 * 管理员审核文章
	 */
	public function approve($id)
	{
		$article = Article::find($id);
        if (!$article) {
            return Redirect::back()->withInput()->with('error', '<strong>文章审核失败。此文章不存在。</strong>');
        }

        try {
            $article->status = Article::STATUS_APPROVED;
            $article->save();
        } catch(Exception $ex) {
            Log::error($ex);
            return Redirect::route('admin.article.view', $id)->with('error', '<strong>文章审核失败。</strong>');
        }
        return Redirect::route('admin.article.view', $id)->with('success', '<strong>文章审核成功。</strong>');  
	}

	/**
	 * 文章审核不通过
	 */
	public function unapprove($id)
	{
		$article = Article::find($id);
        if (!$article) {
            return Redirect::back()->withInput()->with('error', '<strong>文章审核失败。此文章不存在。</strong>');
        }

        try {
            $article->status = Article::STATUS_UNAPPROVED;
            $article->save();
        } catch(Exception $ex) {
            Log::error($ex);
            return Redirect::route('admin.article.view', $id)->with('error', '<strong>文章审核失败。</strong>');
        }
        return Redirect::route('admin.article.view', $id)->with('success', '<strong>文章审核成功。</strong>');  
	}

    public function create()
    {		
		$law_cat_list = Article::getArticleClassList('请选择', 'law_category');
        $type_instrument_list = Article::getArticleClassList('请选择', 'type_instrument');
		$article_class_list = Article::getArticleClassList('请选择', 'article');
 		$down_group_list = Article::getArticleClassList('请选择', 'down_group');
        $this->layout->content = View::make('admin.article.create')->with(compact('law_cat_list', 'article_class_list', 'down_group_list', 'type_instrument_list'));
	}

    public function store()
    {
		$data   = Input::all();
		$rules  = array(
			  'law_cat'    => 'required',
			  'title'    => 'required',
			  'class'    => 'required',
			  'info' => 'required',
			  'keys' => 'required',
			  'content' => 'required',
		 );
		$messages = $this->validatorMessages;
		$validator = Validator::make($data, $rules, $messages);
		if ($validator->fails()) {
			return Redirect::back()->withInput()->withErrors($validator);
		}

		try {
			if( $img = Input::file('img'))
			{
				$upload_root = Config::get('app.upload_root');
				$path = Config::get('app.upload_dir');
				$dir = '/info'.date("/Y/m/", time());
				$upload_result = UploadHelper::uploadImage('img', $upload_root.$path.$dir);

	            if ($upload_result['error'] == 0) {
	            } else {
	                throw new Exception('上传图片失败。');
	            }
				$data['img'] = $path.$dir.$upload_result['files'][0]['filename'];
			}

			if( $article_file = Input::file('article_file'))
			{
				$upload_root = Config::get('app.upload_root');
				$download_path = Config::get('app.download_dir');
				$dir = date("/Y/m/", time());
				$upload_result = UploadHelper::upload('article_file', 
					$upload_root.$download_path.$dir, $allow_exts=['pdf','doc','jpg','jpeg','jpe','png','gif','bmp']);
	            if ($upload_result['error'] == 0) {
	            } else {
	                throw new Exception('上传文件失败。');
	            }
				$data['file_path'] = $download_path.$dir.$upload_result['files'][0]['filename'];
				
				// 把上传文件的信息保存在数据库里面
			    FileAttachment::saveAttachment(
			        $upload_result['files'][0]['ext'],
			        $upload_result['files'][0]['filename'],
			        $data['file_path']);
			}

			$data['from_admin'] = true;

			$article = Article::storeArticle($data);
		} catch (Exception $ex) {
			return Redirect::back()
				->withInput()
				->with('error', '<strong>文章保存失败。</strong>');
		}

		return Redirect::route('admin.article.index')
			->with('success', '<strong>文章保存成功。</strong>');		
    }

	public function view($id)
	{
		$law_cat_list = UtilsHelper::workScope();
		$article_class_list = Article::getArticleClassList('请选择', 'article');
 		$down_group_list = Article::getArticleClassList('请选择', 'down_group');
		$article = Article::find($id);
		$article->class = $article_class_list[$article->class];
		$article->law_cat = UtilsHelper::getWorkScopeName($article->law_cat);
		$this->layout->content = View::make('admin.article.view')->with(compact('law_cat_list', 'article', 'article_class_list', 'down_group_list'));
	}

	public function edit($id)
	{
		$law_cat_list = Article::getArticleClassList('请选择', 'law_category');
        $type_instrument_list = Article::getArticleClassList('请选择', 'type_instrument');
		$article_class_list = Article::getArticleClassList('请选择', 'article');
 		$down_group_list = Article::getArticleClassList('请选择', 'down_group');
		$article = Article::find($id);
		$article->file_path = UtilsHelper::getFile($article->file_path);
		$article->img = UtilsHelper::getImage($article->img, 'img/dfimg.png');
		$this->layout->content = View::make('admin.article.edit')->with(compact('law_cat_list', 'article', 'article_class_list', 'down_group_list', 'type_instrument_list'));
	}

   public function update($id)
   {
		$data   = Input::all();
		$rules  = array(
			  'law_cat'    => 'required',
			  'title'    => 'required',
			  'class'    => 'class',
			  'info' => 'required',
			  'keys' => 'required',
			  'content' => 'required',
		 );
		
		$messages = $this->validatorMessages;
		$validator = Validator::make($data, $rules, $messages);
		if (true || $validator->passes()) {
			$article = Article::find($id);

			try {
				if( $img = Input::file('img'))
				{
					if($article->img)
					{
						File::delete($article->img);
					}
					$upload_root = Config::get('app.upload_root');
					$path = Config::get('app.upload_dir');
					$dir = '/info'.date("/Y/m/", time());
					$upload_result = UploadHelper::uploadImage('img', $upload_root.$path.$dir);
		            if ($upload_result['error'] == 0) {
		            } else {
		                throw new Exception('上传图片失败。');
		            }
					$data['img'] = $path.$dir.$upload_result['files'][0]['filename'];
				}

				if( $article_file = Input::file('article_file'))
				{
					if($article->file_path)
					{
						File::delete($article->file_path);
					}
					$upload_root = Config::get('app.upload_root');
					$download_path = Config::get('app.download_dir');
					$dir = date("/Y/m/", time());
					$upload_result = UploadHelper::upload('article_file', 
						$upload_root.$download_path.$dir, $allow_exts=['pdf','doc','jpg','jpeg','jpe','png','gif','bmp','docx']);
		            if ($upload_result['error'] == 0) {
		            } else {
		                throw new Exception('上传文件失败。');
		            }
					$data['file_path'] = $download_path.$dir.$upload_result['files'][0]['filename'];
					
					// 把上传文件的信息保存在数据库里面
					FileAttachment::saveAttachment(
					    $upload_result['files'][0]['ext'],
					    $upload_result['files'][0]['original_filename'],
					    $data['file_path']);
				}

				$article = Article::updateArticle($id, $data);

			} catch (Exception $ex) {
				Log::error($ex);
				return Redirect::back()
					->withInput()
					->with('error', '<strong>文件上传失败。</strong>');
			}


			return Redirect::route('admin.article.index')
				->with('success', '<strong>文章更新成功。</strong>');	
		} else {
			return Redirect::back()->withInput()->withErrors($validator);
		}
    }

	public function destroy($id)
	{
			$data = App::make('Article')->find($id);
			if (is_null($data))
			{
					return Redirect::back()->with('error', '没有找到对应的文章。');
			} elseif ($data->delete()) {
					return Redirect::back()->with('success', '文章删除成功。');
			} else {
					return Redirect::back()->with('warning', '文章删除失败。');
			}
	}
}
